package shlib

import "unsafe"

const (
	AnyType_Nil = iota
	AnyType_Int
	AnyType_String
	AnyType_Bytes
	AnyType_Pointer
	AnyType_Interface
)

// 可以存储各种基本类型数据的容器类型
type Any struct {
	ty   int        // 实际数据类型，见 AnyType_XXX 常量
	data [3]uintptr // 存放具体数据内容的空间
}

func (this *Any) Type() int {
	return this.ty
}

func (this *Any) AsInt64() int64 {
	return int64(this.data[0])
}

func (this *Any) AsString() string {
	return *(*string)(unsafe.Pointer(&this.data))
}

func (this *Any) AsBytes() []byte {
	return *(*[]byte)(unsafe.Pointer(&this.data))
}

func (this *Any) AsPointer() unsafe.Pointer {
	return unsafe.Pointer(this.data[0])
}

func (this *Any) AsInterface() interface{} {
	return *(*interface{})(unsafe.Pointer(&this.data))
}

func (this *Any) SetInt64(val int64) {
	this.data[0] = uintptr(val)
	this.ty = AnyType_Int
}

func (this *Any) SetString(val string) {
	*(*string)(unsafe.Pointer(&this.data)) = val
	this.ty = AnyType_String
}

func (this *Any) SetBytes(val []byte) {
	*(*[]byte)(unsafe.Pointer(&this.data)) = val
	this.ty = AnyType_Bytes
}

func (this *Any) SetPointer(val unsafe.Pointer) {
	this.data[0] = uintptr(val)
	this.ty = AnyType_Pointer
}

func (this *Any) SetInterface(val interface{}) {
	*(*interface{})(unsafe.Pointer(&this.data)) = val
	this.ty = AnyType_Interface
}

func (this *Any) SetNil() {
	this.ty = AnyType_Nil
}
